package com.ihd.ihardware.view.tzc.health.view;

import android.bluetooth.le.AdvertiseCallback;
import android.bluetooth.le.AdvertiseData;
import android.bluetooth.le.AdvertiseSettings;
import android.bluetooth.le.BluetoothLeAdvertiser;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.ihd.ihardware.R;
import com.ihd.ihardware.app.MyApplication;
import com.ihd.ihardware.common.AppConstans;
import com.ihd.ihardware.common.utils.CalUtils;
import com.ihd.ihardware.common.utils.DataUtils;
import com.ihd.ihardware.common.widget.BindDialog;
import com.ihd.ihardware.common.widget.MemberDialog;
import com.ihd.ihardware.common.widget.MemberDialogListAdapter;
import com.ihd.ihardware.common.widget.ObservableScrollView;
import com.ihd.ihardware.databinding.HealthFragmentBinding;
import com.ihd.ihardware.pojo.DeviceListRes;
import com.ihd.ihardware.pojo.MembersRes;
import com.ihd.ihardware.pojo.ReportRes;
import com.ihd.ihardware.pojo.UserInfoRes;
import com.ihd.ihardware.pojo.WeightRes;
import com.ihd.ihardware.view.tzc.main.view.BalanceActivity;
import com.ihd.ihardware.view.tzc.main.viewmodel.BalanceViewModel;
import com.ihd.ihardware.view.tzc.me.view.AddMemberActivity;
import com.ihd.ihardware.view.tzc.me.view.TargetWeightActivity;
import com.inuker.bluetooth.library.beacon.Beacon;
import com.inuker.bluetooth.library.utils.BluetoothUtils;

import java.math.BigDecimal;
import java.util.List;

import cn.wowjoy.commonlibrary.base.BaseConsumer;
import cn.wowjoy.commonlibrary.base.BaseFragment;
import cn.wowjoy.commonlibrary.rxbus.RxBus;
import cn.wowjoy.commonlibrary.utils.BLEUtils;
import cn.wowjoy.commonlibrary.utils.DensityUtil;
import cn.wowjoy.commonlibrary.utils.DialogUtils;
import cn.wowjoy.commonlibrary.utils.HexUtils;
import cn.wowjoy.commonlibrary.utils.SPUtils;
import cn.wowjoy.commonlibrary.utils.ToastUtils;
import cn.wowjoy.commonlibrary.widget.MDialog;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

public class HealthFragment extends BaseFragment<HealthFragmentBinding, BalanceViewModel> {
    private boolean isVisible = false;
    private BindDialog mBindDialog;
    private UserInfoRes.DataBean ud;
    private Disposable cheng;
    private String originalData;
    private CountDownTimer timer;
    private MemberDialog md;
    private MDialog mAlert;
    private boolean hasCheng = false;
    private AdvertiseData mAdvertiseData;
    private AdvertiseSettings mAdvertiseSettings;
    private static BluetoothLeAdvertiser mBluetoothLeAdvertiser;
    private static AdvertiseCallback mAdvertiseCallback;

    public HealthFragment() {
    }

    public static HealthFragment newInstance(String param1, String param2) {
        HealthFragment fragment = new HealthFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
        }
    }

    @Override
    protected void onCreateViewLazy(Bundle savedInstanceState) {
        if (isVisible)
            ((BalanceActivity) getActivity()).mImmersionBar.statusBarDarkFont(false).init();

        mAdvertiseData = new AdvertiseData.Builder()
                .setIncludeDeviceName(true)
//                .addManufacturerData(0, new byte[]{0x05, 0x09, 0x56, 0x43, 0x48, 0x4D})
//                .addServiceData(ParcelUuid.fromString("0"), new byte[]{0x05, 0x09, 0x56, 0x43, 0x48, 0x4D})
                .build();
        mAdvertiseSettings = new AdvertiseSettings.Builder()
                .setAdvertiseMode(AdvertiseSettings.ADVERTISE_MODE_BALANCED)
                .setConnectable(false)
                .build();
        mAdvertiseCallback = new AdvertiseCallback() {
            @Override
            public void onStartSuccess(AdvertiseSettings settingsInEffect) {
                super.onStartSuccess(settingsInEffect);
            }

            @Override
            public void onStartFailure(int errorCode) {
                super.onStartFailure(errorCode);
            }
        };

        ud = new Gson().fromJson(SPUtils.getString(AppConstans.USER_INFO, ""), UserInfoRes.DataBean.class);
        if (!TextUtils.isEmpty(ud.getAvatar())) {
            Glide.with(this)
                    .load(Uri.parse(ud.getAvatar()))
                    .apply(RequestOptions.circleCropTransform())
                    .into(binding.head);
            binding.headname.setText("我");
            MyApplication.memberId = new MembersRes.DataBean();
            MyApplication.memberId.setAvatar(ud.getAvatar());
            MyApplication.memberId.setRelation(0);
            MyApplication.memberId.setMemberId("");
        }

        binding.close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                binding.noticeLL.setVisibility(View.GONE);
            }
        });

        binding.head.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                md = new MemberDialog(getActivity(), R.style.dialog_bg, MyApplication.membersData, new MemberDialogListAdapter.OnItemClickListener() {
                    @Override
                    public void onItemClick(View view, MembersRes.DataBean data) {
                        md.cancel();
                        if (TextUtils.isEmpty(data.getUserId())) {
                            Intent i = new Intent(getContext(), AddMemberActivity.class);
                            startActivity(i);
                        } else {
                            MyApplication.memberId = data;
                            viewModel.getWeight(MyApplication.memberId.getMemberId());
                            binding.headname.setText(data.getMember());
                            if (!TextUtils.isEmpty(data.getAvatar())) {
                                Glide.with(getActivity())
                                        .load(Uri.parse(data.getAvatar()))
                                        .apply(RequestOptions.circleCropTransform())
                                        .into(binding.head);
                            } else {
                                binding.head.setImageResource(R.drawable.head_defult);
                            }
                        }
                    }
                });
                md.setCanceledOnTouchOutside(true);
                md.setCancelable(true);
                md.show();
            }
        });

        binding.addIV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(getContext(), HandRecordActivity.class);
                startActivity(i);
            }
        });

        binding.reportRL.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                viewModel.report(MyApplication.memberId.getMemberId());
            }
        });

        binding.reportIV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                viewModel.report(MyApplication.memberId.getMemberId());
            }
        });

        binding.hisIV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(getContext(), CountActivity.class);
                i.putExtra("familyId", MyApplication.memberId.getMemberId());
                startActivity(i);
            }
        });

        binding.historyIV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(getContext(), CountHisActivity.class);
                i.putExtra("familyId", MyApplication.memberId.getMemberId());
                i.putExtra("type", "3");
                startActivity(i);
            }
        });

        binding.broadcast.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (hasCheng)
                    isShowWeight(MyApplication.memberId.getAvatar(), MyApplication.memberId.getMember());
                else
                    isShowBind();
            }
        });

        binding.targetIV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(MyApplication.memberId.getMemberId())) {
                    Intent i = new Intent(getContext(), TargetWeightActivity.class);
                    startActivity(i);
                } else {
                    mAlert = DialogUtils.alertDialog(getActivity(), MDialog.DG_TYPE.ALERT, "该功能只针对主角色，是否切换回主角色", "取消", "确定", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            mAlert.cancel();
                        }
                    }, new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            mAlert.cancel();
                            for (MembersRes.DataBean md : MyApplication.membersData) {
                                if ("".equals(md.getMemberId())) {
                                    MyApplication.memberId = md;
                                    viewModel.getWeight(MyApplication.memberId.getMemberId());
                                    binding.headname.setText(md.getMember());
                                    if (!TextUtils.isEmpty(md.getAvatar())) {
                                        Glide.with(getActivity())
                                                .load(Uri.parse(md.getAvatar()))
                                                .apply(RequestOptions.circleCropTransform())
                                                .into(binding.head);
                                    } else {
                                        binding.head.setImageResource(R.drawable.head_defult);
                                    }
                                }
                            }
                        }
                    });
                }
            }
        });

        binding.activeLL.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(MyApplication.memberId.getMemberId())) {
                    Intent i = new Intent(getContext(), WalkActivity.class);
                    i.putExtra("weight", binding.weightTV.getText().toString());
                    startActivity(i);
                } else {
                    mAlert = DialogUtils.alertDialog(getActivity(), MDialog.DG_TYPE.ALERT, "该功能只针对主角色，是否切换回主角色", "取消", "确定", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            mAlert.cancel();
                        }
                    }, new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            mAlert.cancel();
                            for (MembersRes.DataBean md : MyApplication.membersData) {
                                if ("".equals(md.getMemberId())) {
                                    MyApplication.memberId = md;
                                    viewModel.getWeight(MyApplication.memberId.getMemberId());
                                    binding.headname.setText(md.getMember());
                                    if (!TextUtils.isEmpty(md.getAvatar())) {
                                        Glide.with(getActivity())
                                                .load(Uri.parse(md.getAvatar()))
                                                .apply(RequestOptions.circleCropTransform())
                                                .into(binding.head);
                                    } else {
                                        binding.head.setImageResource(R.drawable.head_defult);
                                    }
                                }
                            }
                        }
                    });
                }
            }
        });

        binding.eatLL.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(getContext(), SolutionActivity.class);
                startActivity(i);
            }
        });

        timer = new CountDownTimer(15 * 1000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {

            }

            @Override
            public void onFinish() {
                originalData = "";
            }
        };

        setRx(AppConstans.HANDREPORT, new BaseConsumer<ReportRes>() {
            @Override
            protected void onStart() {
            }

            @Override
            protected void onSuccess(ReportRes mLiveData) {
                Intent i = new Intent(getContext(), ReportActivity.class);
                i.putExtra("report", mLiveData.getData());
                startActivity(i);
            }

            @Override
            protected void onError(Throwable error) {
                ToastUtils.showShort(getContext(), error.getMessage());
            }
        });

        setRx(AppConstans.WEIGHT, new BaseConsumer<WeightRes>() {
            @Override
            protected void onStart() {
            }

            @Override
            protected void onSuccess(WeightRes mLiveData) {
                if (mLiveData.getData() != null) {
                    binding.sportview.setProgress((int) (Float.parseFloat(mLiveData.getData().getWeight()) / 110f * 100));
                    binding.reportRL.setVisibility(View.VISIBLE);
                    binding.emptyRL.setVisibility(View.GONE);
                    binding.weightTV.setText(mLiveData.getData().getWeight());
                    binding.dateTV.setText(mLiveData.getData().getTime());
                    binding.tzlTV.setText(CalUtils.getFat(new BigDecimal(mLiveData.getData().getBmi())).toString() + "%");
                    binding.bmiTV.setText(mLiveData.getData().getBmi());

                    for (MembersRes.DataBean md : MyApplication.membersData) {
                        if (md.getMemberId() != null && md.getMemberId().equals(MyApplication.memberId.getMemberId())) {
                            boolean isWoman = md.getSex() == 1 ? false : true;
                            switch (CalUtils.getBMIDes(isWoman, new BigDecimal(mLiveData.getData().getBmi()))) {
                                case 0:
                                    binding.txTV.setText("您的体型：未知");
                                    if (isWoman)
                                        binding.txIV.setImageResource(R.drawable.girl_0);
                                    else
                                        binding.txIV.setImageResource(R.drawable.boy_0);
                                    break;
                                case 1:
                                    binding.txTV.setText("您的体型：偏瘦");
                                    if (isWoman)
                                        binding.txIV.setImageResource(R.drawable.girl_1);
                                    else
                                        binding.txIV.setImageResource(R.drawable.boy_1);
                                    break;
                                case 2:
                                    binding.txTV.setText("您的体型：标准");
                                    if (isWoman)
                                        binding.txIV.setImageResource(R.drawable.girl_2);
                                    else
                                        binding.txIV.setImageResource(R.drawable.boy_2);
                                    break;
                                case 3:
                                    binding.txTV.setText("您的体型：偏胖");
                                    if (isWoman)
                                        binding.txIV.setImageResource(R.drawable.girl_3);
                                    else
                                        binding.txIV.setImageResource(R.drawable.boy_3);
                                    break;
                                case 4:
                                    binding.txTV.setText("您的体型：肥胖");
                                    if (isWoman)
                                        binding.txIV.setImageResource(R.drawable.girl_4);
                                    else
                                        binding.txIV.setImageResource(R.drawable.boy_4);
                                    break;
                                case 5:
                                    binding.txTV.setText("您的体型：超胖");
                                    if (isWoman)
                                        binding.txIV.setImageResource(R.drawable.girl_5);
                                    else
                                        binding.txIV.setImageResource(R.drawable.boy_5);
                                    break;
                                default:
                                    binding.txTV.setText("您的体型：未知");
                                    if (isWoman)
                                        binding.txIV.setImageResource(R.drawable.girl_0);
                                    else
                                        binding.txIV.setImageResource(R.drawable.boy_0);
                                    break;
                            }
                        }
                    }

                    if ("-1".equals(mLiveData.getData().getBmiTag())) {
                        binding.bmiTag.setVisibility(View.VISIBLE);
                        binding.bmiTag.setImageResource(R.drawable.icon_arrow_down);
                    } else if ("1".equals(mLiveData.getData().getBmiTag())) {
                        binding.bmiTag.setVisibility(View.VISIBLE);
                        binding.bmiTag.setImageResource(R.drawable.icon_arrow_up);
                    } else {
                        binding.bmiTag.setVisibility(View.GONE);
                    }
                } else {
                    binding.weightTV.setText("0.0");
                    binding.reportRL.setVisibility(View.GONE);
                    binding.bmiTag.setVisibility(View.GONE);
                    binding.bmiTV.setText("--");
                    binding.emptyRL.setVisibility(View.VISIBLE);
                    binding.txIV.setImageResource(R.drawable.girl_0);
                    binding.txTV.setText("信息不够，无法判断出您的体型");
                }
            }

            @Override
            protected void onError(Throwable error) {
                ToastUtils.showShort(getContext(), error.getMessage());
            }
        });

        binding.titleLL.getBackground().setAlpha(0);
        binding.mainSV.setOnScollChangedListener(new ObservableScrollView.OnScollChangedListener() {
            @Override
            public void onScrollChanged(ObservableScrollView scrollView, int x, int y, int oldx, int oldy) {
                int alpha = y * 255 / DensityUtil.dip2px(35);
                binding.titleLL.getBackground().setAlpha(alpha > 255 ? 255 : alpha);
            }
        });
    }

    private void isShowBind() {
        mBindDialog = new BindDialog(getActivity(), R.style.dialog_bg, R.layout.dialog_bind, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!BLEUtils.getInstance().isBluetoothOpened()) {
                    Intent i = new Intent(getContext(), BluetoothActivity.class);
                    startActivity(i);
                } else {
                    broadcastBLE();
                    Intent i = new Intent(getContext(), BindingActivity.class);
                    startActivity(i);
                    mBindDialog.cancel();
                }
            }
        }, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mBindDialog.cancel();
            }
        });
        mBindDialog.show();
    }

    private void isShowWeight(String head, String name) {
        broadcastBLE();
        mBindDialog = new BindDialog(getActivity(), R.style.dialog_bg, R.layout.dialog_weight, head, name, new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        }, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
            }
        });
        mBindDialog.show();
    }

    static void stopAdv() {
        if (mBluetoothLeAdvertiser != null)
            mBluetoothLeAdvertiser.stopAdvertising(mAdvertiseCallback);
    }

    private void broadcastBLE() {
        mBluetoothLeAdvertiser = BluetoothUtils.getBluetoothAdapter().getBluetoothLeAdvertiser();
        if (BluetoothUtils.getBluetoothAdapter().isEnabled()) {
            if (mBluetoothLeAdvertiser != null) {
                mBluetoothLeAdvertiser.startAdvertising(mAdvertiseSettings,
                        mAdvertiseData, mAdvertiseCallback);
            } else {
                Log.e("daqi", "该手机不支持ble广播");
            }
        } else {
            Log.e("daqi", "手机蓝牙未开启");
        }
    }

    @Override
    protected void onResumeLazy() {
        super.onResumeLazy();
        cheng = RxBus.getInstance().tObservable(AppConstans.CHENG, Beacon.class)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Beacon>() {
                    @Override
                    public void accept(Beacon beacon) throws Exception {
                        byte[] mByte = new byte[31];
                        System.arraycopy(beacon.mBytes, 0, mByte, 0, beacon.mBytes.length);
                        if (TextUtils.isEmpty(originalData)) {
                            stopAdv();
                            if (DataUtils.isStable(mByte)) {
                                timer.start();
                                originalData = HexUtils.bytesToHex(mByte);
                                Intent i = new Intent(getContext(), MeasureActivity.class);
                                i.putExtra("familyId", MyApplication.memberId.getMemberId());
                                i.putExtra("originalData", originalData);
                                startActivity(i);

                            }
                        }
                    }
                });
        viewModel.members(ud, MyApplication.memberId.getMemberId());

        String temp = SPUtils.getString(AppConstans.DEVICES, "");
        hasCheng = false;
        if (TextUtils.isEmpty(temp)) {
            isShowBind();
        } else {
            List<DeviceListRes.DataBean.ListBean> ddls = new Gson().fromJson(temp, new TypeToken<List<DeviceListRes.DataBean.ListBean>>() {
            }.getType());
            for (DeviceListRes.DataBean.ListBean ddl : ddls) {
                if ("0".equals(ddl.getType()) || "1".equals(ddl.getType())) {
                    hasCheng = true;
                    if (mBindDialog != null && mBindDialog.isShowing())
                        mBindDialog.cancel();
                }
            }
            if (!hasCheng)
                isShowBind();
        }
    }

    @Override
    protected void onPauseLazy() {
        super.onPauseLazy();
        if (cheng != null && !cheng.isDisposed())
            cheng.dispose();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.health_fragment;
    }

    @Override
    protected Class<BalanceViewModel> getViewModelClass() {
        return BalanceViewModel.class;
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        isVisible = isVisibleToUser;
        if (isVisibleToUser && getActivity() != null)
            ((BalanceActivity) getActivity()).mImmersionBar.statusBarDarkFont(false).init();
    }

    @Override
    protected void onDestroyViewLazy() {
        super.onDestroyViewLazy();
        if (mBluetoothLeAdvertiser != null)
            mBluetoothLeAdvertiser.stopAdvertising(mAdvertiseCallback);
        mBluetoothLeAdvertiser = null;
        mAdvertiseCallback = null;
    }
}
